package com.xwj.service.impl;

import com.xwj.action.OrderTccAction;
import com.xwj.domain.Order;
import com.xwj.dto.CommonResult;
import com.xwj.enums.ResultCode;
import com.xwj.feign.StorageFeignClient;
import com.xwj.service.OrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @author xwj
 * @date 2020/11/13
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderTccAction orderTccAction;
    @Autowired
    private StorageFeignClient storageFeignClient;

    @Override
    @GlobalTransactional(name = "create-order", rollbackFor = Exception.class)
    public void create(final Order order) {
        //1、新建订单
        boolean result = orderTccAction.createOrderTccAction(null, order);
        if(!result) {
            throw new RuntimeException("订单创建失败");
        }
        //2、扣减库存
        log.info("开始调用减库存服务");
        CommonResult commonResult = storageFeignClient.decrease(order.getProductId(), order.getCount());
        if (commonResult.getCode() == ResultCode.FAILED.getCode()) {
            throw new RuntimeException("调用减库存服务失败");
        }
        log.info("结束调用减库存服务");
    }
}
